﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraEditors.DXErrorProvider;
using PDNPAS.db;
using System.Data.OracleClient;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;


namespace PDNPAS
{
    public partial class PDNPASFrm : RibbonForm
    {
        private static DataTable userDataTable, authDataTable, menuDataTable, selectedMenuDataTable;
        private Hashtable htMenuState = new Hashtable(); //存放各菜单状态
        private Hashtable htMenuItem = new Hashtable(); //存放各菜单项
        private static string connectStr = "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=210.35.88.92) (PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)))";
        private static string connectUname = "pdnpasuser";
        private static string connectUpwd = "pdnpaspwd";

        public PDNPASFrm()
        {
            InitializeComponent();
            InitSkinGallery();
            InitAuthManageData();
            InitMenuState();
            testAuthMenu("lyl");
        }
        void InitSkinGallery()
        {
            SkinHelper.InitSkinGallery(rgbiSkins, true);
        }

        //初始化整个权限管理模块所需的数据
        private void InitAuthManageData()
        {
            userDataTable = DBHelper.GetQueryResult(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd),
                "select * from view_user");
            authDataTable = DBHelper.GetQueryResult(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd),
                "select * from view_auth");
            menuDataTable = DBHelper.GetQueryResult(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd),
                "select * from view_menu");
            tcgAuthManage.SelectedTabPageIndex = 0;
        }

        //初始化菜单项哈希表，并使所有菜单为不可选状态
        private void InitMenuState()
        {
            htMenuItem.Add(iUserSetting.Caption, iUserSetting);
            htMenuItem.Add(iAuthSetting.Caption, iAuthSetting);
            htMenuState.Clear();
            foreach (DataRow dr in menuDataTable.Rows)
            {
                string menuName = dr["MENUNAME"] as string;
                try
                {
                    htMenuState.Add(menuName, false);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }

        #region
        ///<summary>
        ///用户与权限模块的菜单点击事件
        /// </summary>

        //响应点击用户管理菜单项产生的事件
        private void iUserSetting_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgAuthManage.SelectedTabPageIndex = 0;
            tabUserManage.SelectedTabPageIndex = 0;
            userGridControl.DataSource = userDataTable;
            btnAddUser.Enabled = true;
            btnUpdateUser.Enabled = true;
            btnDeleteUser.Enabled = true;
            btnAlterUserPwd.Enabled = true;
        }

        //响应点击权限管理菜单项产生的事件
        private void iAuthSetting_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgAuthManage.SelectedTabPageIndex = 1;
            tabUserManage.SelectedTabPageIndex = 0;
            authGridControl.DataSource = authDataTable;
            btnAlterAuth.Enabled = true;
            btnAuthToUser.Enabled = true;
            btnAuthToMenu.Enabled = true;
        }

        #endregion

        #region
        ///<summary>
        ///用户信息列表界面的按钮事件
        /// </summary>

        //响应点击添加用户按钮产生的事件
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            //初始化用户角色下拉框
            cmbUserAuth.Properties.Items.Clear();
            int rows = authDataTable.Rows.Count;
            for (int i = 0; i < rows; i++) 
            {
                string authName = (string)authDataTable.Rows[i]["AUTHNAME"];
                cmbUserAuth.Properties.Items.Add(authName);
            }
            //切换到添加用户页面
            tcgAuthManage.SelectedTabPageIndex = 0;
            tabUserManage.SelectedTabPageIndex = 1;
        }

        //响应点击修改用户按钮产生的事件
        private void btnUpdateUser_Click(object sender, EventArgs e)
        {
            DataRow[] dt = userDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须而且只能选择一个用户!");
            }
            else if (dt.Length > 1)
            {
                MessageBox.Show("您只能选择一个用户!");
            }
            else
            {
                //给用户角色下拉框增加数据
                cmbAlterUserAuth.Properties.Items.Clear();
                int rows = authDataTable.Rows.Count;
                for (int i = 0; i < rows; i++)
                {
                    string authName = (string)authDataTable.Rows[i]["AUTHNAME"];
                    cmbAlterUserAuth.Properties.Items.Add(authName);
                }
                //获取当前选中用户的信息，并传递给修改用户界面
                string uid = (string)dt[0]["USERID"];
                string uname = (string)dt[0]["USERNAME"];
                string authname = (string)dt[0]["AUTHNAME"];
                string remark = "";
                try
                {
                    remark = (string)dt[0]["REMARK"];
                }
                catch
                {
                    Console.WriteLine(e);
                }
                txtAlterUserId.Text = uid;
                txtAlterUserName.Text = uname;
                cmbAlterUserAuth.SelectedItem = authname;
                txtAlterUserRemark.Text = remark;
                //设置修改用户标签页选中
                tabUserManage.SelectedTabPageIndex = 2; 
            }
        }

        //响应点击删除用户按钮产生的事件
        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            //判断用户是否选择要删除的用户
            DataRow[] dt = userDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须至少选择一个用户!");
            }
            else
            {
                MessageBoxButtons mbtn = MessageBoxButtons.YesNo;
                DialogResult dResult = MessageBox.Show("确定要删除所选的用户吗?", "确认删除用户", mbtn);
                if (dResult == DialogResult.Yes)
                {
                    for (int i = 0; i < dt.Length; i++)
                    {
                        try
                        {
                            //从数据库中删除用户
                            string uid = (string)dt[i]["USERID"];
                            string sql = String.Format("delete from tuser where userid='{0}'", uid);
                            DBHelper.DeleteRecord(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                        }
                        catch
                        {
                            Console.WriteLine(e);
                        }
                        //从DataTable中删除用户
                        userDataTable.Rows.Remove(dt[i]);
                    }
                }
            }
        }

        //响应点击修改用户密码按钮产生的事件
        private void btnAlterUserPwd_Click(object sender, EventArgs e)
        {
            DataRow[] dt = userDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须而且只能选择一个用户!");
            }
            else if (dt.Length > 1)
            {
                MessageBox.Show("您只能选择一个用户!");
            }
            else
            {
                tabUserManage.SelectedTabPageIndex = 3;
            }
        }

        #endregion

        #region
        ///<summary>
        ///用户管理模块的功能实现
        /// </summary>

        //添加新用户到数据库
        private void btnAddUserOk_Click(object sender, EventArgs e)
        {
            //获取输入的新用户信息
            string uid = this.txtUserId.Text;
            string uname = this.txtUserName.Text;
            string upwd = this.txtUserPwd.Text;
            string authName = this.cmbUserAuth.Text;
            string remark = null;
            if(txtUserRemark.EditValue != null)
                remark = txtUserRemark.Text;
            int authlevel = 3;
            try
            {
                authlevel = int.Parse(""+authDataTable.Select("AUTHNAME='" + authName + "'")[0]["AUTHLEVEL"]);
            }
            catch
            {
                Console.WriteLine(e);
            }
            if (!this.errpInput.HasErrors)
            {
                //将新用户信息插入到数据库中
                string sql = String.Format("insert into tuser(userid,username,password,authlevel,remark) values('{0}','{1}','{2}',{3},'{4}')", uid, uname, upwd, authlevel, remark);
                DBHelper.InsertRecord(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                //更新用户信息列表并显示
                userDataTable.Rows.Add(new object[] { '0', uid, uname, upwd, authName, remark });
                tabUserManage.SelectedTabPageIndex = 0;
                ResetAddUser();
            }
            else
            {
                this.errpInput.ContainerControl.Focus();
            }
        }

        //提交修改后的用户信息到数据库
        private void btnAlterUserOk_Click(object sender, EventArgs e)
        {
            //获取修改后的用户信息
            string uid = this.txtAlterUserId.Text;
            string uname = this.txtAlterUserName.Text;
            string authName = this.cmbAlterUserAuth.Text;
            string upwd = null;
            string remark = null;
            if (txtAlterUserPwd.EditValue != null)
                upwd = txtAlterUserPwd.Text;
            if (txtAlterUserRemark.EditValue != null)
                remark = txtAlterUserRemark.Text;
            int authlevel = 3;
            try
            {
                authlevel = int.Parse("" + authDataTable.Select("AUTHNAME='" + authName + "'")[0]["AUTHLEVEL"]);
            }
            catch
            {
                Console.WriteLine(e);
            }
            if (!this.errpInput.HasErrors)
            {
                //将修改后的用户信息更新到数据库中
                string sql = String.Format("update tuser set username='{0}', password='{1}', authlevel='{2}', remark='{3}' where userid='{4}'", uname, upwd, authlevel, remark, uid);
                DBHelper.UpdateRecord(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                //更新用户信息列表并显示
                DataRow dr = userDataTable.Select("USERID='" + uid + "'")[0];
                dr.BeginEdit();
                dr["USERNAME"] = uname;
                dr["USERPWD"] = upwd;
                dr["AUTHNAME"] = authName;
                dr["REMARK"] = remark;
                dr.EndEdit();
                tabUserManage.SelectedTabPageIndex = 0;
                ResetAlterUser();
            }
            else
            {
                this.errpInput.ContainerControl.Focus();
            }
        }

        //提交修改后的用户密码到数据库
        private void btnAlterPwdOk_Click(object sender, EventArgs e)
        {
            //若输入的数据通过验证，则将新密码提交到数据库
            if (!this.errpInput.HasErrors)
            {
                string newPwd = this.txtNewPwd.Text;
                DataRow dr = userDataTable.Select("SELECTED='1'")[0];
                string uid = (string)dr["USERID"];
                string sql = String.Format("update tuser set password='{0}' where userid ='{1}'", newPwd, uid);
                DBHelper.UpdateRecord(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                dr.BeginEdit();
                dr["USERPWD"] = newPwd;
                dr.EndEdit();
                tabUserManage.SelectedTabPageIndex = 0;
                ResetAlterPwd();
            }
            else
            {
                this.errpInput.ContainerControl.Focus();
            }
        }

        //验证用户修改密码时输入的当前密码是否正确
        private void txtOldPwd_Validating(object sender, CancelEventArgs e)
        {
            string oldPwd = this.txtOldPwd.Text;
            DataRow dr = userDataTable.Select("SELECTED='1'")[0];
            if (!dr["USERPWD"].Equals(oldPwd))
            {
                //e.Cancel = true;
                this.txtOldPwd.SelectAll();
                this.errpInput.SetError(txtOldPwd, "当前密码不正确，请重新输入!");
                this.errpInput.SetIconAlignment(txtOldPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //修改密码时验证用户两次输入的密码是否相同
        private void txtConfirmNewPwd_Validating(object sender, CancelEventArgs e)
        {
            string newPwd = txtNewPwd.Text;
            string confirmNewPwd = txtConfirmNewPwd.Text;
            if (!confirmNewPwd.Equals(newPwd))
            {
                //e.Cancel = false;
                this.txtConfirmNewPwd.SelectAll();
                this.errpInput.SetError(txtConfirmNewPwd, "与前面输入的密码不一致，请重新输入!");
                this.errpInput.SetIconAlignment(txtConfirmNewPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //添加用户时验证用户两次输入的密码是否相同
        private void txtConfirmPwd_Validating(object sender, CancelEventArgs e)
        {
            string upwd = txtUserPwd.Text;
            string confirmUpwd = txtConfirmPwd.Text;
            if (!confirmUpwd.Equals(upwd))
            {
                //e.Cancel = false;
                this.txtConfirmPwd.SelectAll();
                this.errpInput.SetError(txtConfirmPwd, "与前面输入的密码不一致，请重新输入!");
                this.errpInput.SetIconAlignment(txtConfirmPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //修改用户时验证用户两次输入的密码是否相同
        private void txtConfirmAlterPwd_Validating(object sender, CancelEventArgs e)
        {
            string upwd = txtAlterUserPwd.Text;
            string confirmUpwd = txtConfirmAlterPwd.Text;
            if (!confirmUpwd.Equals(upwd))
            {
                //e.Cancel = false;
                this.txtConfirmAlterPwd.SelectAll();
                this.errpInput.SetError(txtConfirmAlterPwd, "与前面输入的密码不一致，请重新输入!");
                this.errpInput.SetIconAlignment(txtConfirmAlterPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //取消添加用户，返回到用户信息显示界面
        private void btnCancelAddUser_Click(object sender, EventArgs e)
        {
            ResetAddUser();
            tabUserManage.SelectedTabPageIndex = 0;
        }

        //放弃修改用户，返回到用户信息显示界面
        private void btnCancelAlterUser_Click(object sender, EventArgs e)
        {
            ResetAlterUser();
            tabUserManage.SelectedTabPageIndex = 0;
        }

        //放弃修改用户密码，返回到用户信息显示界面
        private void btnCancelAlterPwd_Click(object sender, EventArgs e)
        {
            ResetAlterPwd();
            tabUserManage.SelectedTabPageIndex = 0;
        }

        //重置添加用户的信息输入框
        private void ResetAddUser()
        {
            this.txtUserId.Text = "";
            this.txtUserName.Text = "";
            this.txtUserRemark.Text = "";
            cmbUserAuth.SelectedItem = "";
        }

        //重置修改用户的信息输入框
        private void ResetAlterUser()
        {
            this.txtAlterUserId.Text = "";
            this.txtAlterUserName.Text = "";
            this.txtAlterUserPwd.Text = "";
            this.txtConfirmAlterPwd.Text = "";
            this.txtAlterUserRemark.Text = "";
            this.cmbAlterUserAuth.SelectedItem = "";
        }

        //重置修改密码的信息输入框
        private void ResetAlterPwd()
        {
            this.txtOldPwd.Text = "";
            this.txtNewPwd.Text = "";
            this.txtConfirmNewPwd.Text = "";
        }

        #endregion

        #region
        ///<summary>
        ///权限列表界面的按钮事件
        /// </summary>
        
        //响应添加权限按钮的点击事件
        private void btnAddAuth_Click(object sender, EventArgs e)
        {
            tcgAuthManage.SelectedTabPageIndex = 1;
            tabAuthManage.SelectedTabPageIndex = 1;
        }

        //响应修改权限按钮的点击事件
        private void btnAlterAuth_Click(object sender, EventArgs e)
        {
            DataRow[] dt = authDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须而且只能选择一个权限!");
            }
            else if (dt.Length > 1)
            {
                MessageBox.Show("您只能选择一个权限!");
            }
            else 
            {
                //获取当前选中权限的信息，并传递给修改权限界面
                int authlevel = int.Parse("" + dt[0]["AUTHLEVEL"]);
                string authname = (string)dt[0]["AUTHNAME"];
                string remark = dt[0]["REMARK"] as string;
                txtAlterAuthlevel.Text = ""+authlevel;
                txtAlterAuthName.Text = authname;
                txtAlterAuthRemark.Text = remark;
                //设置修改权限标签页选中
                tcgAuthManage.SelectedTabPageIndex = 1;
                tabAuthManage.SelectedTabPageIndex = 2;
            }
        }

        //响应删除权限按钮事件
        private void btnDeleteAuth_Click(object sender, EventArgs e)
        {
            //判断用户是否选择要删除的权限
            DataRow[] dt = authDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须至少选择一个权限!");
            }
            else
            {
                MessageBoxButtons mbtn = MessageBoxButtons.YesNo;
                DialogResult dResult = MessageBox.Show("确定要删除所选的权限吗?", "确认删除权限", mbtn);
                if (dResult == DialogResult.Yes)
                {
                    for (int i = 0; i < dt.Length; i++)
                    {
                        try
                        {
                            //从数据库中删除权限
                            
                        }
                        catch
                        {
                            Console.WriteLine(e);
                        }
                        //从DataTable中删除权限
                        authDataTable.Rows.Remove(dt[i]);
                    }
                }
            }
        }

        //响应用户授权按钮的点击事件
        private void btnAuthToUser_Click(object sender, EventArgs e)
        {
            DataRow[] dt = authDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须而且只能选择一个权限!");
            }
            else if (dt.Length > 1)
            {
                MessageBox.Show("您只能选择一个权限!");
            }
            else
            {
                //先清空lbcUserList和lbcAuthUser的内容
                lbcUserList.Items.Clear();
                lbcAuthUser.Items.Clear();
                //获取当前选择的权限
                string authName = (string)dt[0]["AUTHNAME"];
                this.lblCurAuth.Text = authName;
                //将所有用户添加到lbcUserList列表中
                DataRow[] users = userDataTable.Select();
                foreach (DataRow user in users)
                {
                    lbcUserList.Items.Add(user["USERNAME"]);
                }
                //查找拥有当前权限的用户，将它们从lbcUserList中删除
                DataRow[] curAuthUsers = userDataTable.Select("AUTHNAME='"+authName+"'");
                for (int i = curAuthUsers.Length - 1; i >= 0; i--)
                {
                    //lbcAuthUser.Items.Add(curAuthUsers[i]["USERNAME"]);
                    lbcUserList.Items.Remove(curAuthUsers[i]["USERNAME"]);
                }
                //切换到给用户授予当前权限的界面
                tcgAuthManage.SelectedTabPageIndex = 1;
                tabAuthManage.SelectedTabPageIndex = 3;
            }
        }

        //响应菜单授权按钮的点击事件
        private void btnAuthToMenu_Click(object sender, EventArgs e)
        {
            DataRow[] dt = authDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须而且只能选择一个权限!");
            }
            else if (dt.Length > 1)
            {
                MessageBox.Show("您只能选择一个权限!");
            }
            else
            {
                //初始化系统菜单列表
                tlistMenu.DataSource = menuDataTable;
                tlistMenu.KeyFieldName = "MENUID";
                tlistMenu.ParentFieldName = "PARENTID";
                //显示当前权限
                lblCurAuth_Menu.Text = dt[0]["AUTHNAME"] as string;
                //跳转到菜单授权页面
                tcgAuthManage.SelectedTabPageIndex = 1;
                tabAuthManage.SelectedTabPageIndex = 4;
            }
        }

        #endregion

        #region
        ///<summary>
        ///权限管理模块的功能实现
        /// </summary>

        //修改权限信息
        private void btnAlterAuthOk_Click(object sender, EventArgs e)
        {
            //获取修改后的权限信息
            int authlevel = int.Parse(txtAlterAuthlevel.Text);
            string authName = this.txtAlterAuthName.Text;
            string remark = txtAlterAuthRemark.Text;
            //将修改后的权限信息更新到数据库中
            string sql = String.Format("update tauthority set authname='{0}', remark='{1}' where authlevel={2}", authName, remark, authlevel);
            DBHelper.UpdateRecord(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
            //更新权限信息列表并显示
            DataRow dr = authDataTable.Select("AUTHLEVEL=" + authlevel + "")[0];
            dr.BeginEdit();
            dr["AUTHNAME"] = authName;
            dr["REMARK"] = remark;
            dr.EndEdit();
            //返回到权限信息显示界面
            ResetAlterAuth();
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        //取消修改权限
        private void btnCancelAlterAuth_Click(object sender, EventArgs e)
        {
            ResetAlterAuth();
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        private void ResetAlterAuth()
        {
            txtAlterAuthlevel.Text = "";
            txtAlterAuthName.Text = "";
            txtAlterAuthRemark.Text = "";
        }

        //选择要授予当前权限的用户
        private void btnShiftSelectedToRight_Click(object sender, EventArgs e)
        {
            foreach (int index in lbcUserList.SelectedIndices)
            {
                lbcAuthUser.Items.Add(lbcUserList.GetItem(index));
            }
            for (int i = lbcUserList.SelectedItems.Count - 1; i >= 0; i--)
            {
                lbcUserList.Items.Remove(lbcUserList.SelectedItems[i]);
            }
        }

        //将所有未授权用户移到待授权用户列表中
        private void btnShiftAllToRight_Click(object sender, EventArgs e)
        {
            int count = lbcUserList.Items.Count;
            for (int i = 0; i < count; i++)
            {
                lbcAuthUser.Items.Add(lbcUserList.GetItem(i));
            }
            lbcUserList.Items.Clear();
        }

        //选择取消授予当前权限的用户
        private void btnShiftSelectedToLeft_Click(object sender, EventArgs e)
        {
            foreach (int index in lbcAuthUser.SelectedIndices)
            {
                lbcUserList.Items.Add(lbcAuthUser.GetItem(index));
            }
            for (int i = lbcAuthUser.SelectedItems.Count - 1; i >= 0; i--)
            {
                //lbcUserList.Items.Add(lbcAuthUser.SelectedItems[i]);
                lbcAuthUser.Items.Remove(lbcAuthUser.SelectedItems[i]);
            }
        }

        //将所有待授权的用户移到未授予当前权限用户列表
        private void btnShiftAllToLeft_Click(object sender, EventArgs e)
        {
            int count = lbcAuthUser.Items.Count;
            for (int i = 0; i < count; i++)
            {
                lbcUserList.Items.Add(lbcAuthUser.GetItem(i));
            }
            lbcAuthUser.Items.Clear();
        }

        //给选择的用户授予当前权限
        private void btnAuthUserOk_Click(object sender, EventArgs e)
        {
            //先获得当前权限的等级
            int authlevel = int.Parse("" + authDataTable.Select("AUTHNAME='" + lblCurAuth.Text + "'")[0]["AUTHLEVEL"]);
            //逐个用户授予当前权限,更新到数据库和DataTable中
            int count = lbcAuthUser.Items.Count;
            for (int i = 0; i < count; i++)
            {
                string uname = ""+lbcAuthUser.GetItemValue(i);
                string sql = String.Format("update tuser set authlevel={0} where username='{1}'", authlevel, uname);
                DBHelper.UpdateRecord(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                DataRow dr = userDataTable.Select("USERNAME='"+uname+"'")[0];
                dr.BeginEdit();
                dr["AUTHNAME"] = lblCurAuth.Text;
                dr.EndEdit();
            }
            //授权结束后返回权限主界面
            lblCurAuth.Text = "";
            lbcUserList.Items.Clear();
            lbcAuthUser.Items.Clear();
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        //取消授予当前权限，返回到权限主界面
        private void btnCancelAuthUser_Click(object sender, EventArgs e)
        {
            lblCurAuth.Text = "";
            lbcUserList.Items.Clear();
            lbcAuthUser.Items.Clear();
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        //给选择的菜单授予当前权限
        private void btnAuthMenuOk_Click(object sender, EventArgs e)
        {
            if (gcAuthMenu.DataSource != null && selectedMenuDataTable != null && selectedMenuDataTable.Rows.Count > 0)
            {
                //先获取当前权限的权限等级
                int authlevel = int.Parse("" + authDataTable.Select("AUTHNAME='" + lblCurAuth_Menu.Text + "'")[0]["AUTHLEVEL"]);
                //逐个对选择的菜单进行授权
                foreach (DataRow dr in selectedMenuDataTable.Rows)
                {
                    //获取菜单主键
                    int id = int.Parse("" + dr["ID"]);
                    //先判断表TAuthorization中是否存在该记录，以flag为标记
                    bool flag = true;
                    string sql = String.Format("select count(*) from tauthorization where menuid={0} and authlevel={1}", id ,authlevel);
                    DataTable dt = DBHelper.GetQueryResult(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                    if (!(""+dt.Rows[0][0]).Equals("0"))
                        flag = false;
                    //若不存在该记录，则进行插入
                    if(flag)
                    {
                        sql = String.Format("insert into tauthorization(menuid,authlevel) values({0},{1})", id, authlevel);
                        DBHelper.InsertRecord(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                    }
                }
            }
            //清空菜单授权界面，并跳转到权限主界面
            lblCurAuth_Menu.Text = "";
            tlistMenu.DataSource = null;
            gcAuthMenu.DataSource = null;
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        //取消给菜单授予当前权限
        private void btnCancelAuthMenu_Click(object sender, EventArgs e)
        {
            //清空菜单授权界面，并跳转到权限主界面
            lblCurAuth_Menu.Text = "";
            tlistMenu.DataSource = null;
            gcAuthMenu.DataSource = null;
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        #region
        ///<summary>
        ///菜单授权辅助功能函数
        /// </summary>

        //节点选择事件
        private void tlistMenu_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            //设置与该节点相关的节点状态
            SetCheckedChildNodes(e.Node, e.Node.CheckState);
            SetCheckedParentNodes(e.Node, e.Node.CheckState);
            //将选择的节点添加到待授权菜单信息表中
            selectedMenuDataTable = getSelectedMenu(tlistMenu);
            gcAuthMenu.DataSource = selectedMenuDataTable;
        }

        /// <summary>
        /// 选择某一节点时,该节点的子节点全部选择
        /// 取消某一节点时,该节点的子节点全部取消选择
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="check">节点的选择状态</param>
        private void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i].CheckState = check;
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }

        /// <summary>
        /// 某节点的子节点全部选择时,该节点选择
        /// 某节点的子节点未全部选择时,该节点不选择
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="check">节点的选择状态</param>
        private void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                CheckState parentCheckState = node.ParentNode.CheckState;
                CheckState nodeCheckState;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    nodeCheckState = (CheckState)node.ParentNode.Nodes[i].CheckState;
                    if (!check.Equals(nodeCheckState))//只要任意一个与其选中状态不一样即父节点状态不全选
                    {
                        parentCheckState = CheckState.Indeterminate;
                        break;
                    }
                    parentCheckState = check;//否则（该节点的兄弟节点选中状态都相同），则父节点选中状态为该节点的选中状态
                }
                node.ParentNode.CheckState = parentCheckState;
                SetCheckedParentNodes(node.ParentNode, check);//遍历上级节点
            }
        }

        //存放选择状态菜单ID的集合
        private List<string> tlMenuID = new List<string>();

        /// <summary>
        /// 获取选择状态的菜单ID集合
        /// </summary>
        /// <param name="parentNode">父级节点</param>
        private void GetCheckedMenuID(TreeListNode parentNode)
        {
            if (parentNode.Nodes.Count == 0)
            {
                return;//递归终止
            }

            foreach (TreeListNode node in parentNode.Nodes)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    DataRowView drv = tlistMenu.GetDataRecordByNode(node) as DataRowView;
                    if (drv != null)
                    {
                        string MenuID = drv["MenuID"] as string;
                        tlMenuID.Add(MenuID);
                    }
                }
                GetCheckedMenuID(node);
            }
        }

        //获得当前选择菜单的信息
        private DataTable getSelectedMenu(TreeList treelist)
        {
            //存放选择状态菜单的DataTable
            DataTable dtSelectedMenu = new DataTable();
            dtSelectedMenu.Columns.Add("ID", typeof(int));
            dtSelectedMenu.Columns.Add("MENUID", typeof(string));
            dtSelectedMenu.Columns.Add("MENUNAME", typeof(string));
            dtSelectedMenu.Columns.Add("REMARK", typeof(string));

            //清空存放MenuID的集合
            this.tlMenuID.Clear();
            //如果菜单有内容，则取出处于选择状态的节点内容放到集合中
            if (treelist.Nodes.Count > 0)
            {
                foreach (TreeListNode root in treelist.Nodes)
                {
                    GetCheckedMenuID(root);
                }
            }
            //将集合中的菜单项取出，放到DataTable中以实现展示
            foreach (string menuID in tlMenuID)
            {
                DataRow[] dr = menuDataTable.Select("MENUID='" + menuID + "'");
                int id = int.Parse(""+dr[0]["ID"]);
                string menuName = dr[0]["MENUNAME"] as string;
                string remark = dr[0]["REMARK"] as string;
                dtSelectedMenu.Rows.Add(new object[]{id, menuID, menuName, remark});
            }
            return dtSelectedMenu;
        }

        /// <summary>
        /// 随着分割条的移动，tlistMenu的宽度也随之改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sccAuthMenu_SplitterPositionChanged(object sender, EventArgs e)
        {
            this.tlistMenu.Width = this.sccAuthMenu.Panel1.Width - 5;
        }

        /// <summary>
        /// 自动显示待授权菜单列表行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvAuthMenu_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        #endregion

        #endregion

        //测试权限菜单
        private void testAuthMenu(string uname)
        {
            string filterSql = String.Format("select menuname from view_authmenu where uname = '{0}'", uname);
            DataTable dt = DBHelper.GetQueryResult(DBHelper.GetOracleConnection(connectStr, connectUname, connectUpwd), filterSql);
            foreach (DataRow dr in dt.Rows)
            {
                string menuName = dr["MENUNAME"] as string;
                if (htMenuState.Contains(menuName))
                {
                    htMenuState.Remove(menuName);
                    try
                    {
                        htMenuState.Add(menuName, true);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            //遍历菜单状态哈希表，设置菜单项的状态
            foreach (DictionaryEntry dems in htMenuState)
            {
                foreach (DictionaryEntry demi in htMenuItem)
                {
                    if(demi.Key.Equals(dems.Key))
                    {
                        BarButtonItem btn = demi.Value as BarButtonItem;
                        btn.Enabled = (bool)dems.Value;
                    }
                }
            }
        }

    }
}